<?php

namespace app\admin\controller\referral\log;

use app\admin\service\UserService;
use app\BaseController;
use app\model\ConsultEvaluateModel;
use app\model\DepartmentModel;
use app\model\InterfereUserModel;
use app\model\referral\ReferralLogModel;
use app\model\UserModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 部门选择器
     * @return bool|string
     */
    public function departmentSelector(): bool|string
    {
        try {
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,pid,name')->where('unit_id','=', $this->userData['unit_id'])->select()->toArray();
            return success(buildTree($data));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 用户选择器
     * @return bool|string
     */
    public function userSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'department_id|部门' => 'require'
            ]);
            $UserModel = new UserModel();
            $data = $UserModel->field('id,name')->where('department_id','=', $param['department_id'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 风险程度
     * @return bool|string
     */
    public function levelSelector(): bool|string
    {
        try {
            return success([
                1 => '低风险',
                2 => '中风险',
                3 => '高风险',
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 发起转介
     * @return bool|string
     */
    public function initiate(): bool|string
    {
        $ReferralLogModel = new ReferralLogModel();
        $ReferralLogModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'uid|用户' => 'require',
                'agency_id|机构' => 'require',
                'reason|转介原因' => 'require',
                'level|危险程度' => 'require',
                'describe|情况描述' => 'require',
                'physical_condition|身体情况' => 'require',
                'mental_state|精神状态' => 'require',
                'experience|特殊经历' => 'require',
                'medical_history|病史' => 'require',
                'contacts|联系人' => 'require',
                'contact_number|联系人电话' => 'require',
            ]);
            if (!empty($param['channel']) && !empty($param['channel_id'])){
                switch ($param['channel']){
                    case 3:
                        $InterfereUserModel = new InterfereUserModel();
                        $info = $InterfereUserModel->find($param['channel_id']);
                        if (!$info) throw new \Exception('来源错误！');
                        $info->save([
                            'is_referral' => 1
                        ]);
                        break;
                    case 4:
                        $ConsultEvaluateModel = new ConsultEvaluateModel();
                        $info = $ConsultEvaluateModel->find($param['channel_id']);
                        if (!$info) throw new \Exception('来源错误！');
                        $info->save([
                            'is_referral' => 1
                        ]);
                        break;
                }
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['up_time'] = time();
            $param['time'] = time();
            $ReferralLogModel->insert($param);
            $ReferralLogModel->commit();
            return success();
        } catch (\Exception $e) {
            $ReferralLogModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 转介记录
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            if (!empty($param['name'])){
                $UserModel = new UserModel();
                $uid = $UserModel->where('name|username','like','%'.$param['name'].'%')->column('id');
                if (!empty($uid)){
                    $where[] = ['uid','in',$uid];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['agency_id'])){
                $where[] = ['agency_id','=',$param['agency_id']];
            }
            if (!empty($param['level'])){
                $where[] = ['level','=',$param['level']];
            }
            if (isset($param['is_end']) && strlen($param['is_end']) > 0){
                $where[] = ['is_end','=',$param['is_end']];
            }
            if (!empty($param['reason'])){
                $where[] = ['reason','like','%'.$param['reason'].'%'];
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            if (!empty($param['contacts'])){
                $where[] = ['contacts','like','%'.$param['contacts'].'%'];
            }
            $ReferralLogModel = new ReferralLogModel();
            $query = $ReferralLogModel->where($where);
            $data = $query->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                },
                'agency'
            ])->paginate($param['pageSize'])->toArray();
            if (!empty($data['data'])) {
                $UserService = new UserService($this->app);
                $departmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data['data'] as &$item) {
                    //部门归属
                    $item['department_name'] = $departmentData[$item['department_id']]['all_name'] ?? '';
                    $item['ascription_name'] = $departmentData[$item['department_id']]['ascription_name'] ?? '';
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 记录详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $ReferralLogModel = new ReferralLogModel();
            $data = $ReferralLogModel->with([
                'user',
                'agency'
            ])->find($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除记录
     * @return bool|string
     */
    public function delete(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $ReferralLogModel = new ReferralLogModel();
            if (is_array($param['id'])){
                $ReferralLogModel->where('id','in',$param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $info = $ReferralLogModel->find($param['id']);
                if (!$info) throw new \Exception('参数错误！');
                $info->save([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 导出记录
     * @return bool|string
     */
    public function export(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $ReferralLogModel = new ReferralLogModel();
            $data = $ReferralLogModel->where('id','in',$param['id'])->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                },
                'agency'
            ])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('导出记录');
            // 设置单元格数据
            $sheet->setCellValue('A1', '转介用户');
            $sheet->setCellValue('B1', '性别');
            $sheet->setCellValue('C1', '年龄');
            $sheet->setCellValue('D1', '用户联系方式');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '医院方最新处理时间');
            $sheet->setCellValue('G1', '危机程度');
            $sheet->setCellValue('H1', '转介是否完结');
            $sheet->setCellValue('I1', '转介时间');
            $sheet->setCellValue('J1', '转介原因');
            $sheet->setCellValue('K1', '转介人');
            $sheet->setCellValue('L1', '所在单位');
            $sheet->setCellValue('M1', '所在学部');
            $sheet->setCellValue('N1', '所在部门');
            $sheet->setCellValue('O1', '部门内编号');
            $sheet->setCellValue('P1', '学籍状态');
            $sheet->setCellValue('Q1', '注册账号');
            $UserService = new UserService($this->app);
            $departmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($data as $key => $item) {
                $key = $key + 2;
                //学籍状态
                $student_name = match ($item['student_status']) {
                    0 => '不限',
                    1 => '在读',
                    2 => '已毕业',
                    3 => '已退学',
                    4 => '休学',
                    default => '--',
                };
                $level = match ($item['level']) {
                    1 => '低风险',
                    2 => '中风险',
                    3 => '高风险',
                    default => '--',
                };
                $sheet->setCellValue('A' . $key, $item['user_name']);
                $sheet->setCellValue('B' . $key, $item['sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('C' . $key, $item['age']);
                $sheet->setCellValue('D' . $key, $item['phone']);
                $sheet->setCellValue('E' . $key, $item['id_card']);
                $sheet->setCellValue('F' . $key, date('Y-m-d H:i:s', $item['up_time']));
                $sheet->setCellValue('G' . $key, $level);
                $sheet->setCellValue('H' . $key, $item['is_end']?'已完结':'--');
                $sheet->setCellValue('I' . $key, date('Y-m-d H:i:s', $item['time']));
                $sheet->setCellValue('J' . $key, $item['reason']);
                $sheet->setCellValue('K' . $key, $item['contacts']);
                $sheet->setCellValue('L' . $key, $item['unit_name']);
                $sheet->setCellValue('M' . $key, $departmentData[$item['department_id']]['ascription_name'] ?? '--');
                $sheet->setCellValue('N' . $key, $departmentData[$item['department_id']]['all_name'] ?? '--');
                $sheet->setCellValue('O' . $key, $item['user_number']);
                $sheet->setCellValue('P' . $key, $student_name);
                $sheet->setCellValue('Q' . $key, $item['username']);
            }

            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/referral_log'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            $url = oss('./public' . $save_name . $ext, $ext);
            return success([
                'url' => $url,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}